package com.ybfenpan.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

import java.io.OutputStream;
import java.util.Hashtable;

/**
 * 二维码生成
 *
 * @author lzx
 */
public class QRCodeUtils {

    //二维码图片格式
    private static final String IMG_FORMAT = "png";

    //默认宽度
    private static final int WIDTH = 500;
    //默认长度
    private static final int HEIGHT = 500;

    private static final String SUFFIX = ".shtml";

    public static void generate(String url, int width, int height, OutputStream outputStream) throws Exception {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
        // 内容所使用编码
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, width, height, hints);
        // 生成二维码
        MatrixToImageWriter.writeToStream(bitMatrix, IMG_FORMAT, outputStream);
    }

    public static void generate(String url, OutputStream outputStream) throws Exception {
        generate(url, WIDTH, HEIGHT, outputStream);
    }


    public static void urlGenerate(String name, OutputStream outputStream) throws Exception {
        generate(name + SUFFIX, outputStream);
    }

    private QRCodeUtils() {
    }

}
